//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { Body, fetch } from '@tauri-apps/api/http';


// {
//     "id": 4801,
//     "title": "panlm@DESKTOP-LPGLE1S",
//     "key": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDPBWODPCe+Sx8LIifM8Gwj1PnYQvQA4BDWvhyyGpPJecaIwSMPt7svb5eMp5M9kbaOGtQ+nrtGhR65k/Q/x0GScrOuAq5f65cIDLzK4V1xttKDbd4ptIPTgyE7mzZUF19P+qhpSYwClCWs+Nonk/z/DOrImH3FQFfY3WRorOB5CORMBfv1YovChe/zmop9yhXolej9OBdLBUv4qQD4/l6i46nN7pBMsa6GgsqBCMmECDNoyv8+MKaodGiDL3uGzW5is4meTYiBXmopJ5V0uMkvcLeGHrPzdI/s0m41RcASqpsxIsH/5cge1+egH30/q3iJdHxa1s/jXLklWIWATb9QWMugFOG2zlZ67FkGp1UWWPlggM3XzFQmGbwC020UvpsItaNQcYRR56OWu98mJaUTQ6thCVyPZcGCJweXD2PTPVyeZcClRHSeQcTrWvSBkh2TsPyPTkDOvUPLf25lILHPMuw+NuvFTHgtPpKqdvBtWYyKOaHKFC4xq4BzeLNdqG8= panlm@DESKTOP-LPGLE1S",
//     "created_at": "2024-06-04T08:49:54.901+00:00",
//     "url": "https://api.gitcode.com/v5/user/keys/4801"
// }

export interface GitCodeSshKey {
    key: string;
    id: number;
    title: string;
}

export async function list_ssh_key(accessToken: string): Promise<GitCodeSshKey[]> {
    const reqUrl = `https://api.gitcode.com/api/v5/user/keys?access_token=${encodeURIComponent(accessToken)}&per_page=100`;
    const res = await fetch<GitCodeSshKey[]>(reqUrl, {
        method: "GET",
        timeout: 10,
    });
    if (res.ok && res.status < 300) {
        return res.data;
    } else {
        console.log(res);
        throw "error list user ssh key";
    }
}

export async function add_ssh_key(accessToken: string, title: string, key: string):Promise<void> {
    const res = await fetch<void>(`https://api.gitcode.com/api/v5/user/keys?access_token=${encodeURIComponent(accessToken)}&per_page=100`, {
        method: "POST",
        timeout: 10,
        body: Body.json({
            key,
            title,
        }),
    });
    if (res.ok && res.status >= 200 && res.status < 300) {
        return;
    } else {
        console.log(res);
        throw "error add user ssh key";
    }
}

export async function remove_ssh_key(accessToken: string, keyId: string | number): Promise<void> {
    const res = await fetch<void>(`https://api.gitcode.com/api/v5/user/keys/${keyId}?access_token=${accessToken}`, {
        method: "DELETE",
        timeout: 10,
    });
    if (res.ok && res.status  >= 200 && res.status < 300) {
        return;
    } else {
        console.log(res);
        throw "error list user ssh key";
    }
}